%% This m-file is to merge data together
close all
clear all
clc

data_files={% Read in *_EL.txt
    'SMFe01_scan44_DB_EL.txt'; % Only Fe, No KCl, Before Reflec
    'SMFe01_scan49_DB_EL.txt'; % Only Fe, No KCl, Before Reflec
    'SMFe01_scan76_DB_EL.txt'; % Only Fe, No KCl, after Reflec
    'SMFe01_scan81_DB_EL.txt'; % Only Fe, No KCl, after Reflec
    }

%data_merged_file='SMFe01_44to81_Fe_EL.txt'
data_merged_file='SMFe01_44to81_DB_EL.txt'
% data_merged_file='SMFe01_30to35_Fe_EL.txt'
%data_merged_file='SMFe01_30to35_DB_EL.txt'

% data_merged_file='SMFe01_313to350_Fe_EL.txt'
% data_merged_file='SMFe01_313to350_DB_EL.txt'
%data_merged_file='SMFe01_267to304_Fe_EL.txt'
%data_merged_file='SMFe01_267to304_DB_EL.txt'

%data_merged_file='SMFe01_221to258_Fe_EL.txt'
%data_merged_file='SMFe01_221to258_DB_EL.txt'

%data_merged_file='SMFe01_175to212_Fe_EL.txt'
%data_merged_file='SMFe01_175to212_DB_EL.txt'

%data_merged_file='SMFe01_451to476_DB_EL.txt'
%data_merged_file='SMFe01_451to476_Fe_EL.txt'


MarkerType={'o','s','v','^','d','>','<'}
COLOR={'k','r','b',[0 0.4 0],'m','k','k'}
%%
close all
figure
subplot(1,2,1);
hold on
for k=1:length(data_files)
    data=dlmread(data_files{k});
    x=data(:,1);
    y=data(:,2);
    yerr=data(:,3);
    H=ploterr(x,y,[],yerr,MarkerType{k} ,'hhy',0.2);
    set(H,'color',COLOR{k},'LineWidth',3);
end
hold off
set(gca,'yscale','log')

xdata=zeros(21,1);
ydata=zeros(21,1);
ydata_err=zeros(21,1);
ydata_err_sq=zeros(21,1);
DFlength=length(data_files);
for k=1:DFlength
    data=dlmread(data_files{k})
    xdata=xdata+data(1:21,1);
    ydata=ydata+data(1:21,2);
    ydata_err_sq=ydata_err_sq+data(1:21,3).^2;
end

xdata=xdata/DFlength;
ydata=ydata/DFlength;
ydata_err=sqrt(ydata_err_sq)/DFlength;

subplot(1,2,2)
H=ploterr(xdata,ydata,[],ydata_err,'ko','hhy',0.2);
set(H,'linewidth',3);

%%
Txt_Save(data_merged_file,xdata,ydata,ydata_err)